package cn.dynamicdll
{

	import flash.events.StatusEvent;
	import flash.external.ExtensionContext;
	
	
	public class Extensions
	{
		private static const DLL_ID:String = "cn.dynamicdll.Extensions";
		private var context:ExtensionContext=null;
		
		private static var _this:Extensions =null;
		
		public function Extensions()
		{
			if(null != _this)throw new Error("ane inited error");
		}
	
		public function callCommand(commandName:String, api:String, params:String, apinums:int=0,apilist:Array=null):Object
		{			
			if(this.context)
			{
				//var obj:Object = {};
				return  this.context.call("callCommand", commandName, api, params, apinums, apilist) as Object;
				
			}
			return null; 
		}
		
		public function despose():void
		{
			if(this.context)
			{
				this.context.dispose();
				this.context= null;
			}
		}
		
		private function onStatus(event:StatusEvent):void
		{
			//trace(event.code+" state "+event.level);
			var obj:Object=null;
			if(event.level)
			{
				try{
					obj = JSON.parse(event.level)
				}catch(ex){}
			}
			EventHandler.dispatchEvent(new IEvents(event.code, obj));
		} 
		
		private function initContext():void
		{			
			if(null == this.context)
			{				
				
				this.context = ExtensionContext.createExtensionContext(DLL_ID,"");
				//trace(context)
				this.context.addEventListener(StatusEvent.STATUS, onStatus);
			}
		}
		
		public static function getInstance():Extensions
		{
			if(null == _this)_this = new Extensions;
			_this.initContext();
			return _this;
		}
	}
}